<template>
  <div class="div">
    <div class="div1">
      <div class="div2">
        <h4>小默租房</h4>
        <p>深圳</p>
      </div>
    </div>
    <div class="div3">
      <div>
        <ul>
          <li v-for='i in list' :key="i.id" :class="{ active: select === i.id}"
              @click="handleClick(i.id)"
          >
            {{ i.name }}
          </li>
        </ul>
        <el-input
          style="width: 320px;margin-left:25px;margin-bottom:12px"
          placeholder="小区/商圈/地铁站/地点"
          :prefix-icon="Search"
          @click="router.push('/sou')"
        />
        <div style="margin-left:15px;margin-bottom:9px">
          <el-radio-group v-model="radio">
            <el-radio :value="3">不限</el-radio>
            <el-radio :value="6">1居</el-radio>
            <el-radio :value="9">2居</el-radio>
            <el-radio :value="10">3居(及以上)</el-radio>
          </el-radio-group>
        </div>
        <div style="width:340px;display:flex;margin-left:15px;justify-content: space-between;">
          <div> <el-button type="warning" style="color:white;" class="kan">查看{{ filteredHousesCount }}套房源</el-button></div>
          <div @click="goMap()" class="di"><img src="https://cdn8.axureshop.com/demo2024/2266108/images/%E9%A6%96%E9%A1%B5/u221.svg" class="img">
            <div class="zh">
              <el-icon><Location /></el-icon>
              <h4 style="font-size:14px;margin-left:5px;">地图找房</h4>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="div4">
      <div style="width:370px;margin-left:10px;height:30px;display:flex;padding-top:25px;font-size:12px;color:gray;justify-content: space-between;">
        <div>位置<el-icon size="10"><DCaret /></el-icon></div>
        <div>户型<el-icon size="10"><DCaret /></el-icon></div>
        <div>租金<el-icon size="10"><DCaret /></el-icon></div>
        <div>更多<el-icon size="10"><DCaret /></el-icon></div>
        <div>排序<el-icon size="10"><DCaret /></el-icon></div>
      </div>
      <div
        ref="listRef"
        style="width:370px;margin-left:10px;height: 600px; overflow-y: auto;"
        @scroll="handleScroll"
      >
        <div
          :style="{ height: totalHeight + 'px' }"
          class="virtual-list-container"
        >
          <div
            v-for="(row, rowIndex) in visibleRows"
            :key="rowIndex"
            :style="{ position: 'absolute', top: rowIndex * rowHeight + 'px' }"
          >
            <div
              v-for="item in row"
              :key="item.id"
              class="float-item"
            >
              <img :src="item.img" style="width:172px;height:175px;" @click="goToDetail(item)">
              <div style="background-color:white;">
                <p style="font-size:12px;margin-bottom:5px;margin-left:10px;color:gray;">{{ item.hu ==1?'1':item.hu==2?'2':item.hu==3?'3':'' }}室 58m^{{ item.name }}</p>
                <h5 style="margin-left:10px;margin-bottom:5px;">{{ item.zu==1?'整租':item.zu==2?'合租':item.zu==3?'公寓':item.zu==4?'短租':'' }} | {{ item.zhi }}</h5>
                <div style="margin-bottom:5px;margin-left:10px;color:#7d8abc;background-color:#edeff6;font-size:10px;width:34px;text-align:center">{{ item.you == 1 ? '邻地铁':item.you == 2 ? "有阳台":item.you == 3 ? '有电梯':item.you == 4 ? '精装修':'' }}</div>
                <p style="color:#f57c00;margin-left:10px;"><span style="font-weight:700">{{ item.price }}</span>元/月</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted,watch } from 'vue';
import axios from '../../axios';
import { Search } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';

// 封装防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null;
  return (...args: any[]) => {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn(...args);
    }, delay);
  };
};

const route = useRoute();
const router = useRouter();

const select = ref<number | null>(null);
const list = ref([
  { id: 1, name: '整租' },
  { id: 2, name: '合租/单间' },
  { id: 3, name: '公寓' },
  { id: 4, name: '短租' }
]);
const radio = ref<number>(3);

// 房型选择
const handleClick = (selectId: number) => {
  select.value = selectId;
  updateFilteredHousesCount();
};

// 监听 radio 的变化
const watchRadioChange = () => {
  updateFilteredHousesCount();
};
radio.value = 3; // 初始化 radio 的值
watch(radio, watchRadioChange);

// 渲染数据
const shou = ref([]);
const getshou = () => {
  axios.get('/shou')
    .then(res => {
      shou.value = res.data.shou;
      updateFilteredHousesCount();
    })
    .catch(error => {
      console.error('获取房源数据失败:', error);
    });
};

// 租房与户型
const filteredItems = computed(() => {
  let result = shou.value;
  if (select.value!== null) {
    result = result.filter(item => item.zu === select.value);
  }
  if (radio.value!== 3) {
    result = result.filter(item => {
      if (radio.value === 6) {
        return item.hu === 1;
      } else if (radio.value === 9) {
        return item.hu === 2;
      } else if (radio.value === 10) {
        return item.hu >= 3;
      }
      return false;
    });
  }
  return result;
});

// 房屋数量的变化
const filteredHousesCount = ref(0);
const updateFilteredHousesCount = () => {
  let count = 0;
  if (select.value === null && radio.value === 3) {
    count = shou.value?.length;
  } else {
    const filtered = filteredItems.value;
    count = filtered.length;
  }
  filteredHousesCount.value = count;
};

// 虚拟列表相关
const listRef = ref<HTMLElement | null>(null);
const itemHeight = 300; // 每个项目的高度
const itemsPerRow = 2; // 每行显示的项目数量
const visibleRowsCount = 8; // 可视区域显示的行数
const visibleHeight = visibleRowsCount * itemHeight; // 可视区域的高度

const totalHeight = computed(() => Math.ceil(filteredItems.value.length / itemsPerRow) * itemHeight);
const startRowIndex = ref(0);
const endRowIndex = ref(visibleRowsCount);

const visibleRows = computed(() => {
  const startIndex = startRowIndex.value * itemsPerRow;
  const endIndex = endRowIndex.value * itemsPerRow;
  const rows = [];
  for (let i = startIndex; i < endIndex; i += itemsPerRow) {
    rows.push(filteredItems.value.slice(i, i + itemsPerRow));
  }
  return rows;
});

const rowHeight = itemHeight;
// 防抖
const handleScroll = debounce(() => {
  if (listRef.value) {
    const scrollTop = listRef.value.scrollTop;
    const newStartRowIndex = Math.floor(scrollTop / rowHeight);
    const newEndRowIndex = newStartRowIndex + visibleRowsCount;
    startRowIndex.value = newStartRowIndex;
    endRowIndex.value = newEndRowIndex;
  }
}, 200);

onMounted(() => {
  getshou();
});

const goMap = () => {
  router.push('/taber/map')
}

// 跳转详情页
const goToDetail = (item: any) => {
  localStorage.setItem('detailData', JSON.stringify(item));
  router.push({ path: '/xiang' });
};
</script>

<style scoped>
* {
  margin: 0px;
  padding: 0px;
}
.div {
  width: 390px;
  position: relative;
}
.div1 {
  width: 390px;
  height: 300px;
  background-image: url(../../assets/u203.png);
  background-size: cover;
  overflow: hidden;
  background-position: center;
}
.div2 {
  width: 360px;
  height: 30px;
  margin-left: 15px;
  display: flex;
  color: white;
  margin-top: 49px;
  justify-content: space-between;
  margin-bottom: 43px;
}
.div3 {
  width: 370px;
  height: 190px;
  background-color: white;
  border-radius: 15px;
  position: absolute;
  top: 123px;
  right: 10px;
}
.div4 {
  width: 390px;
  background-color: #f7f7f7;
}
ul {
  list-style: none;
  display: flex;
  justify-content: space-between;
  text-align: center;
  color: #666666;
  background-color: #ebecee;
  font-size: 14px;
  font-weight: 700;
  border-radius: 15px 15px 0 0;
  margin-bottom: 16px;
}
ul li {
  width: 90px;
  height: 36px;
  line-height: 35px;
}
.active {
  color: black;
  border-bottom: 3px solid #f57c00;
  background-color: white;
  border-radius: 15px 15px 0 0;
}
.kan {
  width: 210px;
  height: 40px;
  border-radius: 10px;
  font-weight: 700;
  background-color: #f57c00;
}
.img {
  width: 120px;
  height: 40px;
}
.di {
  position: relative;
}
.zh {
  display: flex;
  position: absolute;
  top: 12px;
  left: 20px;
}
.virtual-list-container {
  position: relative;
}
.float-item {
  float: left;
  width: 175px;
  height: 300px;
  margin-right: 20px;
  margin-bottom: 10px;
}
.float-item:nth-child(2n) {
  margin-right: 0;
}
</style>